<script setup>
import { ref } from 'vue'
import { useEmployeeStore } from '@/stores'
import { employeeUpdatePasswordService } from '@/api/employee'
import { useRouter } from 'vue-router'

// 表单数据
const formModel = ref({
  password: '',
  newPassword: '',
  repassword: ''
})

// 获取当前管理员数据
const employeeStore = useEmployeeStore()
const employeeInfo = employeeStore.employeeInfo

const formRules = {
  password: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { pattern: /^\S{6,15}$/, message: '密码长度6-15位', trigger: 'blur' }
  ],
  newPassword: [
    { pattern: /^\S{6,15}$/, message: '密码长度6-15位', trigger: 'blur' }
  ],
  repassword: [
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15的非空字符',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        // rule是校验规则，value是当前要校验的字段值，callback是回调函数（无论成功还是失败，都需要callback回调）
        // 判断value和当前form中收集的password是否一致
        if (value !== formModel.value.newPassword) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 表单对象
const form = ref()

// 重置表单内容
const resetForm = async () => {
  await ElMessageBox.confirm('你确认重置表单数据吗？', '温馨提示', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  })
  formModel.value = {
    password: '',
    newPassword: '',
    repassword: ''
  }
}

const router = useRouter()

// 提交表单修改
const submitForm = async () => {
  await form.value.validate()
  await employeeUpdatePasswordService({
    password: formModel.value.password,
    newPassword: formModel.value.newPassword,
    id: employeeInfo.id
  }).then(() => {
    ElMessage.success('密码修改成功，即将返回登录界面，请重新登录')

    // 删除登录的管理员信息
    employeeStore.removeEmployeeInfo()
    // 添加cookie，只保存用户名
    const date = new Date()
    date.setTime(date.getTime() + 7 * 24 * 60 * 60 * 1000)
    document.cookie =
      'employeeMe=' +
      JSON.stringify({
        username: employeeInfo.username
      }) +
      ';expires=' +
      date.toUTCString() +
      ';path=/'

    // 添加延迟
    setTimeout(() => {
      router.push('/login')
    }, 1000)
  })
}
</script>

<template>
  <el-card>
    <template #header>
      <h1>设置密码</h1>
    </template>

    <el-container>
      <el-main>
        <el-form
          :model="formModel"
          :rules="formRules"
          label-width="100px"
          size="large"
          ref="form"
          :hide-required-asterisk="true"
        >
          <el-form-item label="原密码" prop="password">
            <el-input
              v-model="formModel.password"
              placeholder="请输入原密码"
              type="password"
              clearable
            ></el-input>
          </el-form-item>

          <el-form-item label="新密码" prop="newPassword">
            <el-input
              v-model="formModel.newPassword"
              placeholder="请输入新密码，若为空则设置默认密码123456"
              type="password"
              clearable
            ></el-input>
          </el-form-item>

          <el-form-item label="确认密码" prop="repassword">
            <el-input
              v-model="formModel.repassword"
              placeholder="请再次输入新密码"
              type="password"
              clearable
            ></el-input>
          </el-form-item>

          <el-form-item style="padding-left: 50px; margin-top: 20px">
            <el-button type="info" @click="resetForm">重置</el-button>
            <el-button type="primary" @click="submitForm">提交</el-button>
          </el-form-item>
        </el-form>
      </el-main>
    </el-container>
  </el-card>
</template>

<style lang="scss" scoped>
.el-card {
  height: 100%;

  .el-main {
    padding: 0;

    .el-form {
      width: 35%;
    }
  }
}
</style>
